package com.company.servlet.v1;

import java.util.ArrayList;
import java.util.List;

public class ServletFilter {
    public static void main(String[] args) {
        Request request = new Request();
        request.str = "request,大家好。<<<<<]]]]]]我们都是996";
        Response response = new Response();
        response.str = "response";
        FilterChain fc = new FilterChain();
        fc.add(new HTMLFilter()).add(new Sensitive());
        fc.doFilter(request, response, fc);
        System.out.println(request.str);
        System.out.println(response.str);

    }
}


class Msg {
    String name;
    String msg;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "Msg{" +
                ", msg='" + msg + '\'' +
                '}';
    }
}

class Request {
    String str;
}

class Response {
    String str;
}


interface Filter {
    boolean doFilter(Request request, Response response, FilterChain filterChain);
}

class HTMLFilter implements Filter {

    @Override
    public boolean doFilter(Request request, Response response, FilterChain filterChain) {
        request.str = request.str.replace("<", "[");
        request.str = request.str.replace(">", "]");

        filterChain.doFilter(request, response, filterChain);
        response.str = response.str + "666";
        return true;
    }
}

class Sensitive implements Filter {

    @Override
    public boolean doFilter(Request request, Response response, FilterChain filterChain) {
        request.str = request.str.replace("996", "955");
        filterChain.doFilter(request, response, filterChain);
        response.str = response.str + "666";
        return true;
    }
}


class FilterChain implements Filter {
    List<Filter> filters = new ArrayList<>();
    int index = 0;

    public FilterChain add(Filter f) {
        filters.add(f);
        return this;
    }

//    public boolean doFilter(Msg m){
//        for (Filter f:
//             filters) {
//           if(!f.doFilter(m)) return false;
//        }
//        return true;
//    }


    @Override
    public boolean doFilter(Request request, Response response, FilterChain filterChain) {
        if (index == filters.size()) return false;
        Filter f = filters.get(index);
        index++;
        return f.doFilter(request, response, filterChain);
    }
}
